// zkmaster
package main

import (
	"container/list"
	"fmt"
	"strings"
	"time"

	"github.com/samuel/go-zookeeper/zk"
)

//var ZK_WATCH_PATH string = "/alogic/global/arm"

type ZkMaster struct {
	zkConnect  *zk.Conn
	appNameMap map[string]*list.List
}

/**
 * 获取一个zk连接
 * @return {[type]}
 */
func GetConnect(zkList []string) (conn *zk.Conn) {
	conn, _, err := zk.Connect(zkList, 10*time.Second)
	if err != nil {
		mainStatic.CHECK_RESTART = true
		fmt.Print("=========(12)=========================")
		fmt.Println(err)

	}
	return
}

//创建ZK
func NewZkMaster(zkList string) *ZkMaster {
	zkStr := strings.Split(zkList, ",")
	conn := GetConnect(zkStr)
	//conn.Create(ZK_WATCH_PATH, nil, 0, zk.WorldACL(zk.PermAll))
	zkMaster := &ZkMaster{
		zkConnect:  conn,
		appNameMap: make(map[string]*list.List),
	}
	return zkMaster
}

//删除zk资源
func (zkMaster *ZkMaster) CloseMaster() {
	zkMaster.zkConnect.Close()
}

func (zkMaster *ZkMaster) CreateZkPath(path string) bool {
	_, error := zkMaster.zkConnect.Create(path, nil, 0, zk.WorldACL(zk.PermAll))
	if error == nil {
		return true
	}
	return false

}

//创建临时zk节点路径
func (zkMaster *ZkMaster) CreateZkSessionPath(path string) bool {
	//fmt.Println("\n>>>>注册Nodepath:" + path + "\n")
	//zkMaster.DeleteZkSessionPath(path)
	_, error := zkMaster.zkConnect.Create(path, nil, zk.FlagEphemeral, zk.WorldACL(zk.PermAll))
	//fmt.Println("########CreateZkSessionPath:" + result)
	//fmt.Println(error)
	if error == nil {
		return true
	}
	return false
}

//是否存在
func (zkMaster *ZkMaster) ExistsZkPath(podMember *Member) bool {
	ports := strings.Split(podMember.Port, "-")
	for _, port := range ports {
		podPath := mainStatic.ZK_WATCH_PATH + "/" + podMember.AppName + "/" + podMember.IP + ":" + port
		ok, _, _ := zkMaster.zkConnect.Exists(podPath)
		if ok == false {
			return false
		}
	}

	return true
}

//删除zk节点路径
func (zkMaster *ZkMaster) DeleteZkSessionPath(path string) bool {
	ok, _, _ := zkMaster.zkConnect.Exists(path)
	if ok == true {
		if zkMaster.zkConnect.Delete(path, 0) != nil {
			//mainStatic.CHECK_RESTART = true
			fmt.Print("====DeleteZkSessionPath=====(13)=========不启动================" + path)
			return false
		}

		return true
	}
	return false
}

func (zkMaster *ZkMaster) CreateZkSessionClientKey(path string) bool {

	//path := mainStatic.ZK_HV_WATCH_PATH + "/client/" + key
	//fmt.Println("\n>>>>zkClientKey:" + path + "\n")
	zkMaster.DeleteZkSessionPath(path)
	return zkMaster.CreateZkSessionPath(path)
	//return true

}
